package com.edu.controller;

import com.edu.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:何包蛋
 * @Date :2022/11/27 - 11 - 27 - 16:21
 */
@Controller
public class UserController {

    @RequestMapping("/register")
    public String userRegister(@Valid User user, BindingResult bindingResult, Model model){
        System.out.println(user.getUserBirthday());
        if(bindingResult.hasErrors()){
            Map<String,String> errorInfo = new HashMap();//存放错误信息 key:出错属性名 value:错误信息
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();//包含了所有 没有通过验证的属性
            for (FieldError fieldError : fieldErrors) {
                //getFiled() 取出错的属性名
                //getDefaultMessage() 取对应的错误信息
                errorInfo.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            model.addAttribute("errors",errorInfo);
            return "forward:/register.jsp";
        }

        System.out.println(user);
        //执行数据库操作 把用户添加到数据库里
        model.addAttribute("user",user);
        return "forward:/success.jsp";
    }

    @RequestMapping("/myregister")
    public String myController(HttpServletRequest request, Model model){
        String userBirthday = request.getParameter("userBirthday");
        System.out.println("2:"+userBirthday);
        model.addAttribute("user",userBirthday);
        return "forward:/index.jsp";
    }
}
